const mongoose = require('mongoose');
const bcrypt = require('bcrypt');

// 构建用户模型
const Schema = mongoose.Schema;
const userSchema = new Schema({
    username: {
        type: String,
        unique: true,
        require: true,
        index: 1
    },
    cname: {
        type: String,
        default: ''
    },
    password: {
        type: String,
        require: true
    },
    token: {
        type: String,
        default: '',
        index: 1
    },
    role: [
        {
            type: Schema.Types.ObjectId,
            ref: 'role'
        }
    ],
    createDate: {
        type: Date,
        default: Date.now
    },
    upDate: {
        type: Date,
        default: Date.now
    },
    delete: {
        type: Boolean,
        default: false
    },
    headImg: {
        type: String,
        default: 'http://dummyimage.com/90x90'
    }
});

// 对密码进行加密,对cname进行处理
userSchema.pre('save', function (next) {
    let user = this;

    user.cname = user.cname.trim();
    if (user.cname.length > 20) {
        user.cname = user.cname.substring(0, 20);
    }

    bcrypt.genSalt(10, function (err, salt) {
        if (err) {
            console.log('加密失败');
            return next(err);
        }
        bcrypt.hash(user.password, salt, function (err, hash) {
            if (err) {
                return next(err);
            }
            user.password = hash;
            next();
        });
    });
});
module.exports = mongoose.model('user', userSchema);
